package net.zjitc.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Administrator on 2017/9/28.
 */
@WebServlet(name = "CookieServlet",urlPatterns = "/cookServlet")
public class CookieServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            response.setContentType("text/html;charset=utf-8");

        /*    Cookie cookie = new Cookie("name","zhansan");
            cookie.setMaxAge(30000);
            response.addCookie(cookie);
            response.getWriter().write("我已经有cookie了...");*/
        /**
         * 1. 获得cooikes
         */
          Cookie[] cookies = request.getCookies();
          String lastTime = null;
        for (int i = 0; cookies != null && i < cookies.length; i++) {
            String name = cookies[i].getName();
            if ("lastAccessTime".equals(name)){ //key
                lastTime = cookies[i].getValue(); //value
                break;
            }
        }
        PrintWriter out = response.getWriter();

        //判断上次访问时间是否为空
        if (lastTime == null){
            out.write("您 是第一次访问");
        }else {
            out.write("您 上次访问的时间是"+lastTime);
        }

        //把当前的时间，要带给浏览器， key - value (String)
        //new Date(); //10221122   2017-2-3 10:10:20   时间---->字符串
        String currentTime = new SimpleDateFormat("yyyy-MM-dd#HH:mm:ss").format(new Date());
        Cookie cookie = new Cookie("lastAccessTime",currentTime);
         response.addCookie(cookie);


    }
}
